import {baseUrl} from"./url.js"
// 上传头像
const uploadFiles =baseUrl + "/upload/upLoadFileByQiNiu";
const uploadFiless =baseUrl + "/upload/upLoadFilesByQiNiu";
const get = function(url, data) {
	return new Promise((ok, err) => {
		let header = {
			'Accept': 'application/json',
			'Content-Type': 'application/json',
		}
		if (uni.getStorageSync("userInfo")) {
			header["Authorization"] ="Bearer "+uni.getStorageSync("userInfo").token
			header["userId"] =uni.getStorageSync("userInfo").userId
		}
		uni.request({
			url: baseUrl + url,
			data: data,
			method: "GET",
			header: header,
			timeout: 15000,
			success: (res) => {
				// 只传给页面正确的数据
				if(res.statusCode==200){
					if (res.data.code == 1 || res.data.code == 200) {
						ok(res.data)
					} else {
						isCode(res.data)
					}
				}else{
					uni.showToast({
						title: '网络错误',
						icon: 'none',
						duration: 1500,
						mask: true
					})
				}
				
			},
			fail: (res) => {
				uni.showToast({
					title: '网络错误',
					icon: 'none',
					duration: 1500,
					mask: true
				})
			},
			complete: (res) => {
				uni.hideLoading()
			}
		})
	})
}
const iget = function(url, data) {
	return new Promise((ok, err) => {
		let header = {
			'Accept': 'application/json',
			'Content-Type': 'application/json',
		}
		if (uni.getStorageSync("userInfo")) {
			header["Authorization"] ="Bearer "+uni.getStorageSync("userInfo").token
			header["userId"] =uni.getStorageSync("userInfo").userId
		}
		uni.request({
			url: baseUrl + url,
			data: data,
			method: "GET",
			header: header,
			timeout:15000,
			success: (res) => {
				//将所有的数据传到页面，按需处理
				ok(res.data)
			},
			fail: (res) => {
				uni.showToast({
					title: '网络错误',
					icon: 'none',
					duration: 1500,
					mask: true
				})
			},
			complete: (res) => {
				uni.hideLoading()
			}
		})
	})
}
const post = function(url, data) {
	return new Promise((ok, err) => {
		let header = {
			'Accept': 'application/json',
			'Content-Type': 'application/json',
		}
		if (uni.getStorageSync("userInfo")) {
			header["Authorization"] ="Bearer "+uni.getStorageSync("userInfo").token
			header["userId"] =uni.getStorageSync("userInfo").userId
		}
		uni.request({
			url: baseUrl + url,
			data: data,
			method: "POST",
			header: header,
			timeout:15000,
			success: (res) => {
				if(res.statusCode==200){
					if (res.data.code==1||res.data.code==200) {
						console.log("res",res.data)
						ok(res.data)
					} else {
						isCode(res.data)
					}
				}else{
					uni.showToast({
						title: '网络错误',
						icon: 'none',
						duration: 1500,
						mask: true
					})
				}
			},
			fail: (res) => {
				uni.showToast({
					title: '网络错误',
					icon: 'none',
					duration: 1000
				})
			},
			complete: (res) => {
				uni.hideLoading()
			}
		})
	})
}
const ipost = function(url, data) {
	return new Promise((ok, err) => {
		let header = {
			'Accept': 'application/json',
			'Content-Type': 'application/json',
		}
		if (uni.getStorageSync("userInfo")) {
			header["Authorization"] ="Bearer "+uni.getStorageSync("userInfo").token
			header["userId"] =uni.getStorageSync("userInfo").userId
		}
		uni.request({
			url: baseUrl + url,
			data: data,
			method: "POST",
			header: header,
			timeout:15000,
			success: (res) => {
				ok(res.data)
			},
			fail: (res) => {
				uni.showToast({
					title: '网络错误',
					icon: 'none',
					duration: 1000
				})
			},
			complete: (res) => {
				uni.hideLoading()
			}
		})
	})
}
// 上传头像
const upimg = (callback, num = 1) => {
	uni.chooseImage({
		count: num, //默认9
		sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
		sourceType: ['album', 'camera'], //从相册选择
		success: (res) => {
			uni.showLoading({
				title: '上传中...'
			});
			console.log(res)
			let tempFilePaths = res.tempFilePaths
			for (var i = 0; i < tempFilePaths.length; i++){
				uni.uploadFile({
					url: uploadFiles,
					filePath: tempFilePaths[i],
					name: 'zrgzHeadImage',
					formData: {
						fileHeadType:"zrgzHeadImage"
					},
					header:{
						'Authorization':"Bearer "+uni.getStorageSync("userInfo").token,
						"userId":uni.getStorageSync("userInfo").userId
					},
					success: (res) => {
						console.log("服务器图片地址", JSON.parse(res.data).data)
						callback(JSON.parse(res.data).data);
					},
					fail: (err) => {},
					complete: () => {
						setTimeout(function() {
							uni.hideLoading();
						}, 250);
					}
				});
			}
		},
		fail: (err) => {
			console.log(err)
		}
	});
}
// 上传图片
const upimgs = (callback, num = 9) => {
	uni.chooseImage({
		count: num, //默认9
		sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
		sourceType: ['album', 'camera'], //从相册选择
		success: (res) => {
			uni.showLoading({
				title: '上传中...'
			});
			console.log(res)
			let tempFilePaths = res.tempFilePaths
			for (var i = 0; i < tempFilePaths.length; i++){
				uni.uploadFile({
					url: uploadFiless,
					filePath: tempFilePaths[i],
					name: 'zrgzHeadImagepl',
					formData: {
						fileHeadType:"zrgzHeadImagepl"
					},
					header:{
						'Authorization':"Bearer "+uni.getStorageSync("userInfo").token,
						"userId":uni.getStorageSync("userInfo").userId
					},
					success: (res) => {
						console.log("服务器图片地址", JSON.parse(res.data).data)
						callback(JSON.parse(res.data).data);
					},
					fail: (err) => {},
					complete: () => {
						setTimeout(function() {
							uni.hideLoading();
						}, 250);
					}
				});
			}
		},
		fail: (err) => {
			console.log(err)
		}
	});
}
// 上传视频
const upvideo = (callback) => {
	uni.chooseVideo({
		sourceType: ['camera', 'album'],
		success: (res) => {
			console.log(res)
			if ((res.duration < 300) && (res.size <= 204800000)) {
				uni.showLoading({
					title: '视频上传中',
					mask: true
				});
				uni.uploadFile({
					url: uploadFiles, //仅为示例，非真实的接口地址
					filePath: res.tempFilePath,
					name: 'Filedata',
					//请求参数
					formData: {
						'user': 'test'
					},
					header:{
						'Authorization':"Bearer "+uni.getStorageSync("userInfo").token,
						"userId":uni.getStorageSync("userInfo").userId
					},
					success: (r) => {
						uni.hideLoading();
						console.log("服务器视频地址", JSON.parse(r.data).data)
						callback(JSON.parse(r.data).data)
					}
				});
			} else {
				if (res.duration > 300) {
					uni.showToast({
						title: '视频时间超过5分钟',
						mask: true,
						icon: "none"
					});
				}
				if (res.duration > 204800000) {
					uni.showToast({
						title: '视频大小超过200M',
						mask: true,
						icon: "none"
					});
				}
			}
		},
		fail: (err) => {}
	});
}

const isCode = function(res){
	let data = res;
	switch (data.code) {
		case '-1':
			uni.removeStorageSync('userInfo');
			uni.removeStorageSync('yunbi');
			let promise = this.tim.logout();
			promise.then(function(imResponse) {
			  console.log("退出登录成功",imResponse.data); // 登出成功
			}).catch(function(imError) {
			  console.warn('logout error:', imError);
			});
			uni.showModal({
				title: '提示',
				content: '当前登录状态已失效，是否跳转登录页面',
				success: function(res) {
					if (res.confirm) {
						console.log('用户点击确定');
						uni.navigateTo({
							url: "/pages/login/login?type=back"
						})
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
			break;
		case '0':
			uni.showToast({
				title: data.msg,
				icon: "none"
			});
			break;
		default:
			uni.showToast({
				title: data.msg,
				icon: "none"
			});
			break;
	}
}
export default {
	get,
	post,
	iget,
	ipost,
	isCode,
	upimg,
	upimgs,
	upvideo,
	uploadFiles
}
